package 面试代码;

public class 三个线程交替循环10次打印ABC {
    //线程交替打印就记住这一个版本，这个版本可以衍生很多变种
    private static Object lock = new Object();
    private static int num = 0;
    public static void main(String[] args) {
        Thread threadA = new Thread(() -> print("A", 0));
        Thread threadB = new Thread(() -> print("B", 1));
        Thread threadC = new Thread(() -> print("C", 2));

        threadA.start();
        threadB.start();
        threadC.start();
    }

    private static void print(String str, int curThread) {
        for (int i = 0; i < 10; i++) {
            synchronized (lock) {
                while (!(num % 3 == curThread)) {
                    try {
                        lock.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                System.out.println(Thread.currentThread().getName() + ": " + str);
                num++;
                lock.notifyAll();
            }
        }
    }
}
